﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;  
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;

namespace RuleCode.ObjectTree
{
    public partial class LanguageSelectForm : Form
    {

        #region 字段
        private static string LabelFilePath = Util_LabelEditor.Instance.LabelFilePath;
        private static string LanguageCategoryName = Util_LabelEditor.Instance.LanguageCategoryFileName;
        //private static string SystemLabelFileID = "RuleCodeSys";
        private static object ChangedRow = "HasChanged";
        private static object IsNewRow = "New";

        private DataTable selectLabelDataTable;
        private DataTable displayLabelDataTable;
        private DataSet dSet;
        #endregion

        #region Value属性
        /// <summary>
        /// 获取或设置 选择窗体所选择的LabelID
        /// </summary>
        public string Value
        {
            get { return this.value; }
            set
            {
                this.value = value;
                this.OnValueChanged(this, new EventArgs());
            }
        }

        public delegate void ValueChangedEventHandler(object sender, EventArgs e);
        public event ValueChangedEventHandler ValueChanged;

        public void OnValueChanged(object sender, EventArgs e)
        {
            if (this.ValueChanged != null)
                ValueChanged(sender, e);
        }
        #endregion

        #region 构造方法
        public LanguageSelectForm()
        {
            InitializeComponent();
        }
        #endregion

        #region 窗体加载
        private void LanguageSelectForm_Load(object sender, EventArgs e)
        {
            try
            {
                bool result = SqlHelper.Instance.ExistTable("City");
                                                
                //显示语言选择框
                StreamReader sRead = new StreamReader(LanguageCategoryName, Encoding.Default, true);
                DataTable lanTable = new DataTable();
                lanTable.Columns.Add("语言");
                lanTable.Columns.Add("描述");
                DataTable displayTable = lanTable.Clone();

                while (!sRead.EndOfStream)
                {
                    string lanName = sRead.ReadLine();
                    string lanDesc = sRead.ReadLine();
                    lanTable.Rows.Add(new string[] { lanName, lanDesc });
                    displayTable.Rows.Add(new string[] { lanName, lanDesc });
                }
                sRead.Close();


                ComboBox_DisplayLan.DisplayMember = "描述";
                ComboBox_DisplayLan.ValueMember = "语言";
                ComboBox_SearchLan.DisplayMember = "描述";
                ComboBox_SearchLan.ValueMember = "语言";
                ComboBox_SearchLan.Items.Clear();
                ComboBox_DisplayLan.Items.Clear();
                ComboBox_DisplayLan.DataSource = displayTable;
                ComboBox_SearchLan.DataSource = lanTable;
                ComboBox_SearchLan.SelectedValue = "ch-zh";
                ComboBox_DisplayLan.SelectedValue = "en-us";

                //设置标签文件ID
                DirectoryInfo dInfo = new DirectoryInfo(LabelFilePath);
                string searchPattern = "RuleCode*ch-zh.txt";
                List<string> allowChangeLanguageFileIDList = new List<string>();
                foreach (FileInfo fInfo in dInfo.GetFiles(searchPattern))
                {
                    string labelFileID = fInfo.Name.Substring(8, 3);
                    if (labelFileID.ToUpper() != "SYS")
                        allowChangeLanguageFileIDList.Add(labelFileID);
                }

                this.LabelFileIDToolStripComboBox.Items.AddRange(allowChangeLanguageFileIDList.ToArray());
                this.LabelFileIDToolStripComboBox.SelectedIndex = 0;
                //end 设置标签文件ID
            }
            catch (Exception error)
            {
                MessageBox.Show(error .Message );
            }

            
            this.selectLabelDataTable.Columns.Add("SelectLabelID");
            this.selectLabelDataTable.Columns["SelectLabelID"].AllowDBNull = false;                      
            this.selectLabelDataTable.Columns.Add("SelectLabelLanguage");
            this.selectLabelDataTable.Columns["SelectLabelLanguage"].AllowDBNull = false;
            this.selectLabelDataTable.Columns.Add("SelectLabel");
            this.selectLabelDataTable.Columns["SelectLabel"].AllowDBNull = false;
            this.selectLabelDataTable.Columns.Add("SelectLabelDescription");

            this.displayLabelDataTable.Columns.Add("DisplayLabelID");
            this.displayLabelDataTable.Columns["DisplayLabelID"].AllowDBNull = false;            
            this.displayLabelDataTable.Columns.Add("DisplayLabelLanguage");
            this.displayLabelDataTable.Columns["DisplayLabelLanguage"].AllowDBNull = false;
            this.displayLabelDataTable.Columns.Add("DisplayLabel");
            this.displayLabelDataTable.Columns.Add("DisplayLabelDescription");
                                                                                                                 
        }
        #endregion        

        private void SearchButton_Click(object sender, EventArgs e)
        {  
            int selectLabelCount = 0;
            this.selectLabelDataTable.Rows.Clear();
            this.displayLabelDataTable.Rows.Clear();

            string searchLabelString = this.SelectContextTextBox.Text;
            if (searchLabelString.Trim() == string.Empty)
            {
                DialogResult dResult = MessageBox.Show("对不起，不能查询空的标签！请重新输入!", "标签输入错误", MessageBoxButtons.OKCancel);
                if (dResult == DialogResult.OK)
                {
                    this.SelectContextTextBox.Focus();
                }
                return;
            }

            DirectoryInfo dInfo=new DirectoryInfo (LabelFilePath );
            List<FileInfo > selectLanFileInfoList = new List<FileInfo >();
            string searchPattern = "RuleCode*" + this.ComboBox_SearchLan.SelectedValue.ToString() + ".txt";
            selectLanFileInfoList = dInfo.GetFiles(searchPattern).ToList();

            if (searchLabelString != "")
            {
                foreach (FileInfo fInfo in selectLanFileInfoList)
                {
                    try
                    {
                        StreamReader selectReader = new StreamReader(fInfo.FullName, Encoding.Default, true);
                        while (!selectReader.EndOfStream)
                        {
                            string lineString = selectReader.ReadLine();
                            string labelDescription = "";
                            if (selectReader.Peek() != '@')
                                labelDescription = selectReader.ReadLine();

                            int separatorIndex = lineString.IndexOf(" ");
                            string labelLanguage = this.ComboBox_SearchLan.SelectedValue.ToString();
                            string labelID = "";
                            string labelContext = "";
                            if (separatorIndex > 0)
                            {
                                labelID = lineString.Substring(0, separatorIndex);
                                labelContext = lineString.Substring(separatorIndex + 1, lineString.Length - 1 - separatorIndex);

                            }
                            else
                            {
                                labelID = lineString;
                            }
                            if (labelContext.Contains(searchLabelString))
                            {
                                selectLabelCount++;
                                this.selectLabelDataTable.Rows.Add(new object[] { labelID, labelLanguage, labelContext, labelDescription });
                            }
                        }
                        selectReader.Close();
                    }
                    catch  
                    {
                    }
                }
 
            }    
            this.SelectCountLabel.Text = selectLabelCount.ToString();
            
            if (selectLabelCount == 0)
            {
                DialogResult dResult= MessageBox.Show("对不起，没有找到您要的标签，新建 请确认！","",MessageBoxButtons .OKCancel );
                if (dResult == DialogResult.OK)
                {
                    this.NewLabelToolStripButton_Click(this, EventArgs .Empty );
                }
                
            }
            
        }

        private void CancelSelectButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void SelectDataGridView_SelectionChanged(object sender, EventArgs e)
        {
            if (this.SelectDataGridView.CurrentRow != null)
            {
                if (this.SelectDataGridView.CurrentRow.Cells["SelectLabel"].Value.ToString() != "")
                {
                    string selectLabelID = this.SelectDataGridView.CurrentRow.Cells["SelectLabelID"].Value.ToString();
                    string selectLabelFileID = selectLabelID.Substring(1, 3);
                    string displayLabelFileName = LabelFilePath + "\\" + "RuleCode" + selectLabelFileID +  this.ComboBox_DisplayLan .SelectedValue.ToString () + ".txt";

                    if (this.displayLabelDataTable.Rows.Count > 0)
                        this.displayLabelDataTable.Rows.Clear();

                    StreamReader sReader = new StreamReader(displayLabelFileName, Encoding.Default, true);
                    while (!sReader.EndOfStream)
                    {
                        string lineString = sReader.ReadLine();
                        string labelDescription = "";
                        if (sReader.Peek() != '@')
                            labelDescription = sReader.ReadLine();

                        int separatorIndex = lineString.IndexOf(' ');
                        string labelLanguage = this.ComboBox_DisplayLan .SelectedValue.ToString ();
                        string labelID = "";
                        string labelContext = "";
                        if (separatorIndex > 0)
                        {
                            labelID = lineString.Substring(0, separatorIndex);
                            labelContext = lineString.Substring(separatorIndex, lineString.Length - separatorIndex);
                        }
                        else
                        {
                            labelID = lineString;
                        }


                        if (labelID == selectLabelID)
                        {


                            this.displayLabelDataTable.Rows.Add(new string[] { labelID, labelLanguage, labelContext, labelDescription });
                            sReader.Close();
                            return;
                        }
                    }
                    sReader.Close();

                }
            }
            else
            {
                this.displayLabelDataTable.Rows.Clear();
            
            }
           
        }

        private void SetNullButton_Click(object sender, EventArgs e)
        {
            DialogResult dResult = MessageBox.Show("您确认要清除当前搜索结果吗？", "", MessageBoxButtons.OKCancel);
            if (dResult == DialogResult .OK )
            {
                this.selectLabelDataTable.Rows.Clear();
                this.displayLabelDataTable .Rows.Clear();
            }
        }

        private void SelectedButton_Click(object sender, EventArgs e)
        {
            if (this.SelectDataGridView.CurrentRow != null)
                this.Value = this.SelectDataGridView.CurrentRow.Cells["SelectLabelID"].Value.ToString();
            else
                this.Value = "";
            this.Close();
        }

        private void NewLabelToolStripButton_Click(object sender, EventArgs e)
        {
            this.selectLabelDataTable.Rows.Clear();

            //string newLabelFileName = LabelFilePath + "\\" + "RuleCode" + LabelFileIDToolStripComboBox.Text + this.ComboBox_SearchLan .SelectedValue .ToString () + ".txt";
            ////StreamWriter sWriter = new StreamWriter(newLabelFileName, true, Encoding.Default);
            //StreamReader sReader = new StreamReader(newLabelFileName ,Encoding .Default ,true);
            //string lineString = "";
            //while (!sReader.EndOfStream)
            //{
            //    lineString = sReader.ReadLine();
            //    if (sReader.Peek() != '@')
            //        sReader.ReadLine();
            //}
            //sReader.Close();

            //int separatorIndex=lineString .IndexOf (' ');

            //long labelIDNumber = 0;
            //string newlabelID = "";
            //string newlabelLan = this.ComboBox_SearchLan .SelectedValue .ToString ();
            //if (separatorIndex > 0)
            //{
            //    labelIDNumber = long.Parse(lineString.Substring(4, separatorIndex - 4));
            //    newlabelID = lineString.Substring(0, 4) + (labelIDNumber + 1).ToString();
            //}
            //else
            //{
            //    labelIDNumber = long.Parse(lineString.Substring(4, lineString .Length-4));
            //    newlabelID = lineString.Substring(0, 4) + (labelIDNumber + 1).ToString();
            //}

            string newlabelID = "@"+LabelFileIDToolStripComboBox .SelectedItem .ToString ()+ Util.GetNewLabelID.ToString () ;
            string newlabelLan = this.ComboBox_SearchLan.SelectedValue.ToString();
            DataRow dRow = this.selectLabelDataTable.NewRow();
            dRow["SelectLabelID"] = newlabelID;
            dRow["SelectLabel"] = SelectContextTextBox.Text.Trim ();
            dRow["SelectLabelLanguage"] = newlabelLan;
       
            this.selectLabelDataTable.Rows.InsertAt(dRow, 0);
                       
            this.SelectDataGridView.Focus();
            //this.SelectDataGridView.Rows[1].Selected = false;
            //this.SelectDataGridView.Rows[0].Selected = true;
            this.SelectDataGridView.Rows[0].Tag = IsNewRow;
            
            //this.SelectDataGridView.Focus();
            this.SelectDataGridView.Rows[0].Cells["SelectLabel"].Selected = true ;
            this.SelectDataGridView.BeginEdit(true);


            this.displayLabelDataTable.Rows.Clear();
            //this.DisplayDataGridView.Rows.Clear();
            DataRow dRow2 = this.displayLabelDataTable.NewRow();
            dRow2 ["DisplayLabelID"]=newlabelID ;
            dRow2["DisplayLabel"] = SelectContextTextBox.Text.Trim();
            dRow2["DisplayLabelLanguage"] = this.ComboBox_DisplayLan  .SelectedValue .ToString ();
            this.displayLabelDataTable .Rows.Add (dRow2 );
            //this.DisplayDataGridView.Rows.Add(new object[] { newlabelID,  this.ComboBox_DisplayLan .SelectedValue.ToString (), "", "" });
            this.DisplayDataGridView.Rows[0].Tag = IsNewRow;
            
            
        }    

        private void SaveLabelToolStripButton_Click(object sender, EventArgs e)
        {
            
        }   


        private void DeleteLabelToolStripButton_Click(object sender, EventArgs e)
        {
            
            string labelFileID = this.LabelFileIDToolStripComboBox.Text;
            
            if (this.SelectDataGridView.CurrentRow != null)
            {
                string label = this.SelectDataGridView.CurrentRow.Cells["SelectLabel"].Value.ToString();

                if (label != "")
                {
                    //删除文件中的数据
                    string labelID = this.SelectDataGridView.CurrentRow.Cells["SelectLabelID"].Value.ToString();
                    DirectoryInfo dInfo = new DirectoryInfo(LabelFilePath);
                    string searchPattern = "RuleCode" + labelFileID + "*.txt";
                    foreach (FileInfo fInfo in dInfo.GetFiles(searchPattern))
                    {
                        string fileName = fInfo.FullName;
                        string bakFileName = fileName.TrimEnd(".txt".ToCharArray()) + ".bak";



                        StreamReader sReader = new StreamReader(fInfo.FullName, Encoding.Default, true);
                        StreamWriter bakWriter = new StreamWriter(File.Create(bakFileName), Encoding.Default);

                        while (!sReader.EndOfStream)
                        {
                            string description = "";
                            string lineString = sReader.ReadLine();
                            if (sReader.Peek() != '@')
                                description = sReader.ReadLine();

                            string fileLableID="";
                            if (lineString.IndexOf(' ') > 0)
                                fileLableID = lineString.Substring(0, lineString.IndexOf(' '));
                            else
                                fileLableID = lineString;


                            if (fileLableID != labelID)
                            {
                                bakWriter.WriteLine(lineString);
                                if (description != "")
                                    bakWriter.WriteLine(description);
                            }
                        }

                        sReader.Close();
                        bakWriter.Close();

                        FileInfo bakInfo = new FileInfo(bakFileName);
                        fInfo.Delete();
                        bakInfo.CopyTo(fileName);
                        bakInfo.Delete();

                    }
                    //end 删除文件中的数据
                }

                //删除表中的数据
                int index = this.SelectDataGridView.CurrentRow.Index;
                this.SelectDataGridView.Rows.RemoveAt(index);
            }
            
        }
  

        private void SelectDataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if(this.SelectDataGridView .CurrentRow !=null)
                if (this.SelectDataGridView.CurrentRow.Tag==null)
                    this.SelectDataGridView.CurrentRow.Tag = ChangedRow ;
        }

        private void DisplayDataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if(this.DisplayDataGridView .CurrentRow!=null)
                if (this.DisplayDataGridView.CurrentRow.Tag == null)
                    this.DisplayDataGridView.CurrentRow.Tag = ChangedRow ;
        }


        private void SelectDataGridView_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {

            if (this.SelectDataGridView.Rows[e.RowIndex].Cells["SelectLabel"].Value.ToString().Trim() == "")
            {
                MessageBox.Show("'查找结果'表中的'标签'不能为空和空格！请重新输入");
                e.Cancel = true;
                this.SelectDataGridView.Rows[e.RowIndex].Cells["SelectLabel"].Selected = true;
                this.SelectDataGridView.BeginEdit(true);
            }
            
        }

        private void SelectDataGridView_RowValidated(object sender, DataGridViewCellEventArgs e)
        {
            string labelFileID = this.selectLabelDataTable.Rows[e.RowIndex]["SelectLabelID"].ToString().Substring(1, 3);
            string selectLabelFileName = LabelFilePath + "\\" + "RuleCode" + labelFileID + this.ComboBox_SearchLan .SelectedValue .ToString () + ".txt";
            string displayLabelFileName =   LabelFilePath + "\\" + "RuleCode" + labelFileID + this.ComboBox_DisplayLan .SelectedValue .ToString () + ".txt";
            if (this.SelectDataGridView.Rows[e.RowIndex].Tag != null)
            {
                //this.DisplayDataGridView.CurrentRow.Tag = this.SelectDataGridView.Rows[e.RowIndex].Tag;
                this.SaveDataGridViewChange(this.SelectDataGridView, selectLabelFileName);
                //if (this.DisplayDataGridView.CurrentRow.Tag == IsNewRow)
                //{
                //    this.DisplayDataGridView.CurrentRow.Tag = ChangedRow;
                //    this.DisplayDataGridView.CurrentRow.Cells["DisplayLabel"].Selected = true;
                //    this.DisplayDataGridView.BeginEdit(true);
                //} 
                if (this.SelectDataGridView.Rows[e.RowIndex].Tag == IsNewRow)
                {
                    this.DisplayDataGridView.CurrentRow .Tag = IsNewRow ;
                    SaveDataGridViewChange(this.DisplayDataGridView, displayLabelFileName);
                    this.DisplayDataGridView.CurrentRow.Tag =  ChangedRow ;
                }
                this.DisplayDataGridView.CurrentRow.Cells["DisplayLabel"].Selected = true;
                this.DisplayDataGridView.BeginEdit(true);
                this.SelectDataGridView.Rows[e.RowIndex].Tag = ChangedRow;
            }
        }
        

        private void DisplayDataGridView_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {

            if (this.DisplayDataGridView["DisplayLabel", e.RowIndex].Value.ToString().Trim() == "")
            {
                MessageBox.Show("'结果显示'表中的'标签'不能为空和空格！请重新输入");
                e.Cancel = true;
                this.DisplayDataGridView.BeginEdit(true);
            }
        }

        private void DisplayDataGridView_RowValidated(object sender, DataGridViewCellEventArgs e)
        {
            string labelFileID = this.displayLabelDataTable.Rows[e.RowIndex]["DisplayLabelID"].ToString().Substring(1, 3);
            string displayLabelFileName = LabelFilePath + "\\" + "RuleCode" + labelFileID  +  this.ComboBox_DisplayLan .SelectedValue.ToString () + ".txt";

            if (this.DisplayDataGridView.Rows[e.RowIndex].Tag != null)
            {
                this.SaveDataGridViewChange(this.DisplayDataGridView, displayLabelFileName);
                this.DisplayDataGridView.Rows[e.RowIndex].Tag = null;
            }
        }

        private void SearchEqualToolStripButton_Click(object sender, EventArgs e)
        {
            int selectLabelCount = 0;
            this.selectLabelDataTable.Rows.Clear();
            this.displayLabelDataTable.Rows.Clear();


            DirectoryInfo dInfo = new DirectoryInfo(LabelFilePath);
            List<FileInfo> selectLanFileInfoList = new List<FileInfo>();
            string searchPattern = "RuleCode*" + this.ComboBox_SearchLan .SelectedValue .ToString () + ".txt";
            selectLanFileInfoList = dInfo.GetFiles(searchPattern).ToList();
            string searchLabelString = this.SelectContextTextBox.Text;

            if (searchLabelString != "")
            {
                foreach (FileInfo fInfo in selectLanFileInfoList)
                {
                    StreamReader selectReader = new StreamReader(fInfo.FullName, Encoding.Default, true);
                    while (!selectReader.EndOfStream)
                    {
                        string lineString = selectReader.ReadLine();
                        string labelDescription = "";
                        if (selectReader.Peek() != '@')
                            labelDescription = selectReader.ReadLine();

                        int separatorIndex = lineString.IndexOf(" ");
                        string labelLanguage = this.ComboBox_SearchLan .SelectedValue .ToString ();  
                        string labelID = "";
                        string labelContext = "";
                        if (separatorIndex > 0)
                        {
                            labelID = lineString.Substring(0, separatorIndex);
                            labelContext = lineString.Substring(separatorIndex+1, lineString.Length-1- separatorIndex);

                        }
                        else
                        {
                            labelID = lineString;
                        }
                        if (labelContext==searchLabelString)
                        {
                            selectLabelCount++;
                            this.selectLabelDataTable.Rows.Add(new object[] { labelID, labelLanguage, labelContext, labelDescription });
                        }
                    }
                    selectReader.Close();
                }

            }
            else
            {
                DialogResult dResult = MessageBox.Show("对不起，不能查询空的标签！请重新输入!", "标签输入错误", MessageBoxButtons.OKCancel);
                if (dResult == DialogResult.OK)
                {
                    this.SelectContextTextBox.Focus();
                }
            }
            this.SelectCountLabel.Text = selectLabelCount.ToString();

            if (selectLabelCount == 0)
            {
                DialogResult dResult = MessageBox.Show("对不起，没有找到您要的标签，新建 请确认！", "", MessageBoxButtons.OKCancel);
                if (dResult == DialogResult.OK)
                {
                    this.NewLabelToolStripButton_Click(this, new EventArgs());
                }

            }
        }   
       
        private void SelectContextTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                this.SearchEqualToolStripButton_Click(this, new EventArgs());
        }

        #region 保存数据的辅助方法
        /// <summary>
        /// 保存DataGridView 当前修改的记录
        /// </summary>
        /// <param name="dGridView"></param>
        /// <param name="fileName"> 包含当前路径的文件名  例如：LabelFile\\RuleCodeSysCh-Zh.txt</param>
        private void SaveDataGridViewChange(DataGridView dGridView, string fileName)
        {
            string labelID = dGridView.CurrentRow.Cells[0].Value.ToString().Trim ();
            string label = dGridView.CurrentRow.Cells[2].Value.ToString().Trim();
            string description = dGridView.CurrentRow.Cells[3].Value.ToString().Trim();

            //新的记录行
            if (dGridView.CurrentRow.Tag == IsNewRow)
            {
                FileStream fStream = new FileStream(fileName, FileMode.Open);
                fStream.Lock(0,fStream.Length);
                fStream.Seek(-1, SeekOrigin.End);
                int endInt = fStream.ReadByte();
                char endChar = Convert.ToChar(endInt );

                StreamWriter sWriter = new StreamWriter(fStream,Encoding.Default );
                if (endChar != '\n')
                    sWriter.WriteLine();   
                sWriter.WriteLine(labelID + " " + label);
                if (description.Trim() != "")
                    sWriter.WriteLine(description);
                fStream.Unlock(0, fStream.Length);
                sWriter.Flush();
                
                fStream.Close();

                string newFileName = fileName;
                newFileName = newFileName.TrimStart((LabelFilePath + "\\").ToCharArray());
                string fileID = newFileName.Substring(0, 11);
                string searchPattern = fileID + "*.txt";

                DirectoryInfo dInfo = new DirectoryInfo(LabelFilePath);
                foreach (FileInfo fInfo in dInfo.GetFiles(searchPattern))
                {
                    if (fInfo.Name != newFileName)
                    {
                        FileStream oStream = new FileStream(fInfo.FullName, FileMode.Open );
                        oStream.Lock(0, oStream.Length);
                        oStream.Seek(-1, SeekOrigin.End);
                        endInt = oStream.ReadByte();
                        endChar = Convert.ToChar(endInt );
                        StreamWriter oWriter = new StreamWriter(oStream, Encoding.Default);
                        if (endChar != '\n')
                            oWriter.WriteLine();
                        oWriter.WriteLine(labelID);
                        oWriter.Close();
                    }
                }
                //dGridView.CurrentRow.Tag = null;
            }
            else if (dGridView.CurrentRow.Tag == ChangedRow)
            {                

                StreamReader oldFileReader = new StreamReader(fileName, Encoding.Default);   
                string allStr = oldFileReader.ReadToEnd();
                oldFileReader.Close();

                string newLabelStr = labelID +" "+label;
                if(description .Trim ()!=string.Empty )
                    newLabelStr +="\r\n"+description ;
                newLabelStr += "\r\n";

                string labelPrefix = labelID.Substring(0, 4);
                int labelIdIndex = allStr.IndexOf(labelID);
                int nextRowIndex = allStr.IndexOf(labelPrefix, labelIdIndex + 1);

                string oldLabelStr = string.Empty;  string newAllStr=string.Empty ;
                if (labelIdIndex >= 0)
                {
                    if (nextRowIndex > labelIdIndex)
                        oldLabelStr = allStr.Substring(labelIdIndex, nextRowIndex - labelIdIndex);
                    else
                        oldLabelStr = allStr.Substring(labelIdIndex, allStr.Length - labelIdIndex);
                    newAllStr = allStr.Replace(oldLabelStr, newLabelStr);
                }
                else
                    newAllStr = allStr.TrimEnd(Environment.NewLine.ToCharArray()) + Environment.NewLine + newLabelStr;
                
                StreamWriter oldWriter = new StreamWriter(fileName,false , Encoding.Default);
                oldWriter.Write(newAllStr);
                oldWriter.Close();
                

                //以下是原来的方法
                //FileStream oldStream = new FileStream(fileName, FileMode.Open);
                //StreamReader oldFileReader = new StreamReader(oldStream, Encoding.Default);
                //oldStream.Lock(0, oldStream.Length);
                //string newFileName = fileName;
                //newFileName = newFileName.TrimEnd("txt".ToCharArray()) + "_" + Guid.NewGuid().ToString("N");
                //newFileName += "bak";
                //FileStream newStream;
                //if (!File.Exists(newFileName))
                //    newStream = File.Create(newFileName);
                //else
                //    newStream = new FileStream(newFileName, FileMode.Open); 
                //StreamWriter newFileWriter = new StreamWriter(newStream, Encoding.Default);

                //while (!oldFileReader.EndOfStream)
                //{
                //    string lineString = oldFileReader.ReadLine();
                //    string filedescription = "";
                //    if (oldFileReader.Peek() != '@')
                //        filedescription = oldFileReader.ReadLine();

                //    string fileLabelID = "";
                //    if (lineString.IndexOf(' ') > 0)
                //        fileLabelID = lineString.Substring(0, lineString.IndexOf(' '));
                //    else
                //        fileLabelID = lineString;

                //    if (fileLabelID == labelID)
                //    {
                //        newFileWriter.WriteLine(labelID + " " + label);
                //        if (description.Trim() != "")
                //            newFileWriter.WriteLine(description);
                //    }
                //    else
                //    {
                //        newFileWriter.WriteLine(lineString);
                //        if (filedescription != null)
                //            if (filedescription.Trim() != "")
                //                newFileWriter.WriteLine(filedescription);
                //    }
                //}
                //oldFileReader.Close();
                //newFileWriter.Close();

                //FileInfo oldFileInfo = new FileInfo(fileName);
                //oldFileInfo.Delete();
                //FileInfo newFileInfo = new FileInfo(newFileName);
                //newFileInfo.MoveTo(fileName);

                //dGridView.CurrentRow.Tag = null;
            }

            
        }
        #endregion
    }

   
}
